package top.hcode.hoj.utils.crypt;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;

public class AesEncryUtil {

    private static final String CIPHER_ALGORITHM = "AES";

    // BASE64编码
    private static final Base64 base64 = new Base64();

    public static Key getSecretKey(String key) throws Exception {
        if (key == null) {
            throw new Exception("密钥不能为空");
        }
        String DES = "AES";
        KeyGenerator keyGenerator = KeyGenerator.getInstance(DES);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(key.getBytes(StandardCharsets.UTF_8));
        keyGenerator.init(secureRandom);
        return keyGenerator.generateKey();
    }

    public static String encrypt(String data, String key) {
        String res_str = "";
        try {
            Key securekey = getSecretKey(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(1, securekey);
            byte[] bt = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            res_str = base64.encodeToString(bt).replaceAll("\\s", "");
        } catch (Exception e) {
            try {
                throw new Exception("加密失败，请检查参数");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return res_str;
    }

    public static String detrypt(String data, String key) {
        String res_str = "";
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            Key securekey = getSecretKey(key);
            cipher.init(2, securekey);
            byte[] res = base64.decode(data);
            res = cipher.doFinal(res);
            res_str = new String(res).replaceAll("\\s", "");
        } catch (Exception e) {
            try {
                throw new Exception("解密失败，请检查参数");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return res_str;
    }
}
